

#include "mainlaser.h"
#include "gopaupau.h"

#include <stdio.h>
#include <stdlib.h>
#include <GL/gl.h>

void rayDisable(Ray *toBeRemoved, Ray *prev)
{
	if(prev==NULL) // head to be removed
		rays_enabled_head = toBeRemoved->next;
	else
	  prev->next = toBeRemoved->next;
	  
	toBeRemoved->next = rays_disabled_head;
	rays_disabled_head = toBeRemoved;
}

Ray *moreRays(int listSize)
{
	Ray *head = NULL;
	int loop;
	Ray *tmp;

    for(loop=0; loop<listSize; loop++)
    {

		if ((tmp = malloc(sizeof(*tmp))) == NULL) {
      		printf("failed to alloc memory for main laser beam\n");
      		(void)exit(EXIT_FAILURE);
    	}

    	tmp->x = 0.0f;
    	tmp->y_tail = 0.0f;
    	tmp->length = 30.0f;
    	tmp->intensity = 50.0f;
    	
    	tmp->next = head;
    	head = tmp;
    }
    printf("allocated %d more rays\n", listSize);
    return(head);
}

Ray *rayGetNew() 
{
	if(rays_disabled_head==NULL)
	{
		rays_disabled_head = moreRays(50);
	}
	Ray *tmp = rays_enabled_head;
	rays_enabled_head = rays_disabled_head;
	rays_disabled_head = rays_disabled_head->next;
	rays_enabled_head->y_hit = 0;
	rays_enabled_head->next = tmp;
	return rays_enabled_head;
}


void raysInit()
{
	rays_enabled_head = NULL;
	rays_disabled_head = moreRays(50);
}

void raysDrawUpdate()
{
	Ray *ray;
	Ray *prev = NULL;
	ray = rays_enabled_head;
	float fake_tail;
  
	while(ray!=NULL)
	{
		// punainen tuli: glColor3f(1.0f,0.8f, 0.2f);
		
		
		//if(ray->intensity > 0.5)
		//	glColor3f(ray->intensity - 0.5,1.0f,0.0f);
		//else
			glColor3f(1.0f,(ray->intensity / 10.0f)+0.9f, ray->intensity);
		glLoadIdentity();
		
		
		glTranslatef(ray->x,ray->y_tail,0.0f);
		glBegin(GL_LINES);
		if(ray->y_tail > (player.y -30))
			fake_tail = (player.y -30) - ray->y_tail;
		else
			fake_tail = 0;
		glVertex2d(0, fake_tail);
		
		int deleteThisRay = 0;
		
		if(ray->y_hit < 0.01f)
			glVertex2d(0, -ray->length);
		else
		{
			glVertex2d(0, ray->y_hit - ray->y_tail);
			deleteThisRay = 1;
			//rayDisable(ray, prev);
		}
		glEnd();
	
		ray->y_tail -= 20;
		
	  	if(ray->y_tail < 0 || deleteThisRay)
	  	{
	  		rayDisable(ray, prev);
	  		if(prev!=NULL)
	  			ray = prev->next;
	  		else
	  			ray = rays_enabled_head;
	  	}
	  	else
	  	{
	  		prev = ray;
	  		ray = ray->next;
	    }	
	}
}	

void rayShoot(int power)
{
	int loop;
	Ray *ray;
	for(loop=0; loop<=(power/2); loop++)
	{
		ray = rayGetNew();
		//printf("%f\n",ray->intensity);
		ray->length = rand()%30 + 20; // max = 50
		ray->x = player.x + rand() % power - (power/2);
		ray->intensity = rand()%1000 / 1000.0f;
		ray->y_tail = player.y + rand() % (int)ray->length-30;
	}
}


